<!--
/**
* Copyright (C) 2022-2023 Timber Chain Cloud (TimberCLD). All Rights Reserved.
* 
* @author: luoweijian
* @email: 807301075@qq..com
* @site: https://www.timbercld.com/
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* 
* http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
*  limitations under the License.
*/
-->
<template>
  <el-dialog v-model="options.visible" :title="!formData.id ? t('add') : t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form v-loading="false" :model="formData" :rules="formRules" ref="formRef" @keyup.enter="submitDataFormHandle()" label-width="120px">
      <el-form-item prop="beanName" :label="t('scheduler.beanName')">
        <el-input v-model="formData.beanName" :placeholder="t('scheduler.beanNameTips')"></el-input>
      </el-form-item>
      <el-form-item prop="params" :label="t('scheduler.params')">
        <el-input v-model="formData.params" :placeholder="t('scheduler.params')"></el-input>
      </el-form-item>
      <el-form-item prop="cronExpression" :label="t('scheduler.cronExpression')">
        <el-input v-model="formData.cronExpression" :placeholder="t('scheduler.cronExpressionTips')"></el-input>
      </el-form-item>
      <el-form-item prop="comment" :label="t('scheduler.comment')">
        <el-input v-model="formData.comment" :placeholder="t('scheduler.comment')"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="options.visible = false">{{ t('cancel') }}</el-button>
      <el-button type="primary" @click="submitDataFormHandle()">{{ t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { ResType } from '@/utils/request';
import { ref, reactive, nextTick, watch } from 'vue';
import debounce from 'lodash/debounce';
import type { ElForm } from 'element-plus';
import { ElMessage, FormRules } from 'element-plus';
import { schedulerApi } from '@/api/global';

// #region 类型
type FormData = {
  id: string;
  beanName: string;
  params: string;
  cronExpression: string;
  comment: string;
  status: number;
};
// #endregion

// #region 属性
const emit = defineEmits<{
  refreshPageHandle: [];
}>();

const formRef = ref<InstanceType<typeof ElForm> | null>(null);

const { t } = useI18n();

const dialogId = ref('0');
// 页面配置
const options = reactive({
  loading: false,
  visible: false,
});
// 表单数据
const formData = reactive<FormData>({
  id: '',
  beanName: '',
  params: '',
  cronExpression: '',
  comment: '',
  status: 0,
});
// 校验规则
const formRules = reactive<FormRules<FormData>>({
  beanName: [{ required: true, message: t('validate.required'), trigger: 'blur' }],
  cronExpression: [{ required: true, message: t('validate.required'), trigger: 'blur' }],
});
// #endregion

// #region 方法
watch([() => dialogId.value], (val1) => {
  formData.id = val1[0];
});

// 获取信息
const getSchedulerInfo = () => {
  schedulerApi.getSchedulerInfo(formData.id).then(async (res) => {
    if (res?.code === 0) {
      await nextTick();
      Object.assign(formData, res.data);
    } else {
      ElMessage.error(res.msg);
    }
    setTimeout(() => {
      options.loading = false;
    }, 500);
  });
};

const init = async () => {
  options.visible = true;
  options.loading = true;
  await nextTick();
  formRef.value?.resetFields();
  if (formData.id) {
    getSchedulerInfo();
  }
};

// 新增日志
function insertScheduler() {
  return new Promise<ResType<unknown>>((resolve, reject) => {
    schedulerApi
      .insertScheduler(formData)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => [reject(err)]);
  });
}
// 更新日志
function updateScheduler() {
  return new Promise<ResType<unknown>>((resolve, reject) => {
    schedulerApi
      .updateScheduler(formData)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => [reject(err)]);
  });
}

// 表单提交
function submit() {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      options.loading = true;
      let res;
      if (formData.id) {
        res = await updateScheduler();
      } else {
        res = await insertScheduler();
      }
      if (res?.code !== 0) {
        ElMessage.error(res.msg);
      } else {
        ElMessage.success(t('prompt.success'));
        options.visible = false;
        emit('refreshPageHandle');
      }
    }
  });
}

const submitDataFormHandle = debounce(submit, 1000, { leading: true, trailing: false });

defineExpose({
  init,
  dialogId,
});
// #endregion
</script>
